package com.realbrand.net.realbrandpay.ui.activity.shopcar;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.TextView;

import com.realbrand.net.realbrandpay.R;
import com.realbrand.net.realbrandpay.adapter.ShopCarAdapter;
import com.realbrand.net.realbrandpay.base.BaseActivity;
import com.realbrand.net.realbrandpay.base.FirstActivity;
import com.realbrand.net.realbrandpay.bean.MyBean;
import com.realbrand.net.realbrandpay.bean.ScanBean;
import com.realbrand.net.realbrandpay.bean.ShopcarBean;
import com.realbrand.net.realbrandpay.db.DBManger;
import com.realbrand.net.realbrandpay.ui.activity.login.LoginActivity;
import com.realbrand.net.realbrandpay.ui.activity.mall.MallActivity;
import com.realbrand.net.realbrandpay.ui.activity.mall.MallCarActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.WalletActivity;
import com.realbrand.net.realbrandpay.ui.activity.wallet.set.WalletLogoutActivity;
import com.realbrand.net.realbrandpay.untils.Constant;
import com.realbrand.net.realbrandpay.untils.Static;
import com.realbrand.net.realbrandpay.zxing.app.CaptureActivity;
import com.realbrand.net.realbrandpay.zxing.util.L;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2017/6/20.
 */

public class ShopCarActivity extends FirstActivity {
    @BindView(R.id.shopcar_tv_Merchant)
    TextView shopcarTvMerchant;
    @BindView(R.id.shopcar_bt_scanMerchant)
    Button shopcarBtScanMerchant;
    @BindView(R.id.shopCar_listView)
    ExpandableListView shopCarListView;
    @BindView(R.id.shopcar_tv_money)
    TextView shopcarTvMoney;
    @BindView(R.id.shopcar_bt_count)
    Button shopcarBtCount;
    @BindView(R.id.shopcar_roolBar)
    Toolbar shopcarRoolBar;
    @BindView(R.id.shopcar_toolBar_tv_clean)
    TextView shopcarToolBarTvClean;

    //用于判断是扫商品码还是扫商家码的标识,true代表商品码，false代表商家码
    public static boolean mBoolean = true;

    @BindView(R.id.shopcar_tv_scan)
    TextView shopcarTvScan;
    @BindView(R.id.shopcar_tv_mall)
    TextView shopcarTvMall;
    @BindView(R.id.shopcar_tv_my)
    TextView shopcarTvMy;
    @BindView(R.id.shopcar_tv_mallCar)
    TextView shopcarTvMallCar;
//    @BindView(R.id.shopcar_tv_gradevin)
//    TextView shopcarTvGradevin;

    private List<MyBean> datas;//数据源
    private ShopCarAdapter adapter;//自定义适配器


    List<ShopcarBean> query; //数据库的数据集合

    //二级列表
    List<List<ScanBean>> scanLists;
    ArrayList<ScanBean> scanList;

    public DBManger dbManger;
    //点击加号跳转到扫码界面的Code
    public static final int RequestCode = 003;
    //扫描商家二维码
    public static final int SCAN_RESULT = -2;

    public static final String SENDMONEY = "send_money";

    //判断商品是否已被添加到商品列表
    private boolean isExist = true;
    /**
     * 创建观察者
     * 用来实时更改总共需要支付的金额
     *
     * @param savedInstanceState
     */
    private DataSetObserver sumObserver = new DataSetObserver() {

        //当Adapter的notifyDataSetChanged();方法执行时被调用
        @Override
        public void onChanged() {
            super.onChanged();
            double money = 0.00;
            for (int i = 0; i < datas.size(); i++) {
                double v = Double.parseDouble(datas.get(i).getBean().getPrice()) * datas.get(i).getCount();
                money += v;
            }
            shopcarTvMoney.setText(new DecimalFormat("0.00").format(money));
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        L.d(L.TAG, "onCreate方法");
        setContentView(getLayoutId());
        ButterKnife.bind(this);
        shopcarRoolBar.setTitle("");
//        shopcarRoolBar.setNavigationIcon(R.drawable.ic_back);
        setSupportActionBar(shopcarRoolBar);
//        shopcarRoolBar.setNavigationOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                Intent intent_scan = new Intent(ShopCarActivity.this, CaptureActivity.class);
//                Bundle bundle_scan = new Bundle();
//                bundle_scan.putString(Static.BundleKey, Static.BundleValue);
//                intent_scan.putExtras(bundle_scan);
//                startActivityForResult(intent_scan, RequestCode);
//            }
//        });
        //取出从扫码界面传过来的数据
        String scanMer = getIntent().getStringExtra("scanMer");
        if (scanMer != null) {
            shopcarTvMerchant.setText(scanMer);
        }


        //初始化时从数据库取出购物车的数据
        dbManger = new DBManger(this);
        query = dbManger.query();
        L.d(L.TAG, query.size() + "这是数据库数据的数量");
        Map<String, Integer> map = new HashMap<>();//做统计
        for (ShopcarBean scarBean : query) {
            map.put(scarBean.getName(), map.get(scarBean.getName()) == null ? 1 : map.get(scarBean.getName()) + 1);
        }
        //遍历map
        datas = new ArrayList<MyBean>();
        scanLists = new ArrayList<>();
        for (String key : map.keySet()) {//map.keySet() 获取所有的key
            MyBean bean = new MyBean();
            Integer count = map.get(key);
            scanList = new ArrayList<>();
            for (ShopcarBean g : query) {
                if (g.name.equals(key)) {
                    bean.setBean(g);
                    bean.setCount(count);
                    ScanBean scanBean = new ScanBean();
                    scanBean.setScan(g.getScan());
                    scanList.add(scanBean);
                }
            }

//            for (int i = 0; i < query.size(); i++) {
//                if (query.get(i).getName().equals(key)){
//                    bean.setBean(query.get(i));
//                    bean.setCount(count);
//
//                }
//            }
            datas.add(bean);
            scanLists.add(scanList);
        }
        adapter = new ShopCarAdapter(scanLists, datas, this, dbManger);
        shopCarListView.setAdapter(adapter);
//        adapter = new TestELVAdapter(scanLists, datas, this,dbManger);
//        shopCarListView.setAdapter(adapter);
        shopCarListView.setGroupIndicator(null);
        adapter.registerDataSetObserver(sumObserver);
        adapter.notifyDataSetChanged();
        adapter.setOnAddNum(this);
        adapter.setOnSubNum(this);
        adapter.setOnRemove(this);
//        //设置默认展开
        if (datas!=null&scanLists!=null&&adapter!=null) {
            int groupCount = shopCarListView.getCount();
            for (int i = 0; i < groupCount; i++) {
                shopCarListView.expandGroup(i);
            }
        }
        shopCarListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
            @Override
            public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                String scan = scanLists.get(groupPosition).get(childPosition).getScan();
                ShopcarBean bean = dbManger.selectScan(scan);
                Intent intent = new Intent(ShopCarActivity.this, CommodityDetailsActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("bean", bean);
                intent.putExtras(bundle);
                startActivity(intent);
                return false;
            }
        });
        //点击不能收缩
//        shopCarListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
//            @Override
//            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
//                return true;
//            }
//        });
        setOnClick();

    }

    @Override
    protected void onResume() {
        super.onResume();
//        if (datas!=null&scanLists!=null&&adapter!=null) {
//            int groupCount = shopCarListView.getCount();
//            for (int i = 0; i < groupCount; i++) {
//                shopCarListView.expandGroup(i);
//            }
//        }
    }

    boolean b;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // if(resultCode == Activity.RESULT_OK) {
        L.d(L.TAG, "请求码是：" + requestCode + "设置结果码是：" + resultCode);
        if (requestCode == RequestCode) {
            if (resultCode == Activity.RESULT_OK) {
                ShopcarBean g = (ShopcarBean) data.getExtras().getSerializable(CaptureActivity.BEAN_KEY);
                adapter.notifyDataSetChanged();
                boolean mBoolean =true; //根据该标识来决定是否要判断该商品要添加到商品列表
                boolean mBool = true;//根据该标识来决定该商品种类是否在商品列表中
                if (g != null) {
                    //先判断该商品的二维码有没有被添加到商品列表
                    if (scanLists.size() > 0) {
                        for (int a = 0; a < scanLists.size(); a++) {
                            for (int b = 0; b < scanLists.get(a).size(); b++) {
                                if (g.getScan().equals(scanLists.get(a).get(b).getScan())) {
                                    //如果该商品的二维码已经被添加到商品列表，则提示该商品已经被扫描过
                                    Static.toast(ShopCarActivity.this, "该商品已被添加到商品列表，请重新扫码");
                                    mBoolean = false;
                                    mBool = false;
                                    break;
                                } else {
                                    //如果该商品的二维码没有被添加到商品列表，则mBoolean=true;
//                                    mBoolean = true;
                                }
                            }
                        }
                    } else {
//                        mBool = true;
                    }
                    //如果mBoolean=true,表示该商品的二维码没有被添加到购物车列表
                    //再来判断商品列表中是否有该商品的种类
                    if (mBoolean) {
                        for (int c = 0; c < datas.size(); c++) {
                            if (g.getName().equals(datas.get(c).getBean().getName())) {
                                //根据该商品的商品名去判断商品列表中是否有该类商品，如果有则直接将该类商品的数量加一，然后加该商品的二维码添加到集合中
                                datas.get(c).setCount(datas.get(c).getCount() + 1);
                                ScanBean scanBean = new ScanBean();
                                scanBean.setScan(g.getScan());
                                scanLists.get(c).add(scanBean);
                                mBool = false;
                                break;
                            } else {
                                //如果商品列表中没有该类商品，则将mBool=true；
                                mBool = true;
                            }
                        }
                    }
                    //如果mBool=true,则表示商品列表中没有该类商品
                    //然后将该商品添加到商品列表中
                    if (mBool) {
                        MyBean myBean = new MyBean();
                        myBean.setCount(1);
                        myBean.setBean(g);
                        datas.add(myBean);
                        //将该类商品的二维码添加到集合中
                        ScanBean bean = new ScanBean();
                        bean.setScan(g.getScan());
                        List<ScanBean> list = new ArrayList<>();
                        list.add(bean);
                        scanLists.add(list);
                    }
                    adapter.notifyDataSetChanged();

                }

            } else if (resultCode == SCAN_RESULT) {
                //获取到商家收款二维码
                String scanMerchant = data.getExtras().getString(Static.VALUE_SCANMERCHANT);
                L.d(L.TAG, "商家二维码" + scanMerchant);
                shopcarTvMerchant.setText(scanMerchant);
            }
        }

    }

    @Override
    protected int getLayoutId() {
        return R.layout.shopcar_activity;
    }

    @Override
    protected void setOnClick() {
        shopcarBtScanMerchant.setOnClickListener(this);
        shopcarBtCount.setOnClickListener(this);
        shopcarToolBarTvClean.setOnClickListener(this);
        shopcarTvMall.setOnClickListener(this);
        shopcarTvScan.setOnClickListener(this);
        shopcarTvMy.setOnClickListener(this);
        shopcarTvMallCar.setOnClickListener(this);
//        shopcarTvGradevin.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Object tag = v.getTag();
        switch (v.getId()) {
            //扫描商家码
            case R.id.shopcar_bt_scanMerchant:
                mBoolean = false;
                Intent intent_merchant = new Intent(ShopCarActivity.this, CaptureActivity.class);
                Bundle bundle_merchant = new Bundle();
                bundle_merchant.putString(Static.BundleKey, Static.VALUE_SCANMERCHANT);
                intent_merchant.putExtras(bundle_merchant);
                startActivityForResult(intent_merchant, RequestCode);
                break;
//            //继续扫码
//            case R.id.shopcar_bt_scan:
//                mBoolean = true;
//                Intent intent_scan = new Intent(ShopCarActivity.this, CaptureActivity.class);
//                Bundle bundle_scan = new Bundle();
//                bundle_scan.putString(Static.BundleKey, Static.BundleValue);
//                intent_scan.putExtras(bundle_scan);
//                startActivityForResult(intent_scan, RequestCode);
//                break;
            //去结算
            case R.id.shopcar_bt_count:
                if (datas.size() != 0) {
                    mBoolean = true;
                    //获取商家
                    String store = shopcarTvMerchant.getText().toString();//扫商家码获取的商家名称
                    String stroeForCommdity = datas.get(0).getBean().getStore();//商品信息提供的商家名称
                    //将购物车内商品总额存入本地数据
                    SharedPreferences sharedPreferences = getSharedPreferences(Constant.shareName, MODE_PRIVATE);
                    SharedPreferences.Editor edit = sharedPreferences.edit();
                    edit.putString(Constant.shopCarMoney, shopcarTvMoney.getText().toString());
                    edit.putString("store", datas.get(0).getBean().getStore());
                    edit.commit();
                    //获取购物车内所有商品的所属商家名，对比是否一致
                    boolean b = true;
                    List<ShopcarBean> query = new DBManger(ShopCarActivity.this).query();
                    for (int i = 0; i < query.size(); i++) {
                        if (!query.get(0).getStore().equals(query.get(i).getStore())) {
                            b = false;
                            break;
                        }
                    }
                    if (b) {
                        //判断是否扫过商家收款码
                        if (TextUtils.isEmpty(store)) {
                            //判断用户是否登录
                            if (LoginActivity.isLogin) {
                                Intent intent_count = new Intent(ShopCarActivity.this, CheckOutActivity.class);
                                Bundle bundle=new Bundle();
                                bundle.putString("forWhere","check");
                                intent_count.putExtras(bundle);
                                startActivity(intent_count);
                                finish();
                            } else {
                                goLogin();
                            }
                        } else {
                            //对比商家码是否相同
                            if (store.equals(stroeForCommdity)) {
                                if (LoginActivity.isLogin) {
                                    Intent intent_count = new Intent(ShopCarActivity.this, CheckOutActivity.class);
                                    Bundle bundle=new Bundle();
                                    bundle.putString("forWhere","check");
                                    intent_count.putExtras(bundle);
                                    startActivity(intent_count);
                                    finish();
                                } else {
                                    goLogin();
                                }
                            } else {
                                Static.toast(ShopCarActivity.this, "收款方与商品销售店不符不能结算");
                            }
                        }
                    } else {
                        Static.toast(ShopCarActivity.this, "商品所属店不一致，无法结算");
                    }
                } else {
                    Static.toast(ShopCarActivity.this, "请扫描商品进行结算");
                }
                break;
            //点击Item加号继续扫描添加商品
            case R.id.shopcar_bt_listview_item_add:
                mBoolean = true;
                Intent intent_add = new Intent(ShopCarActivity.this, CaptureActivity.class);
                Bundle bundle_add = new Bundle();
                bundle_add.putString(Static.BundleKey, Static.BundleValue);
                intent_add.putExtras(bundle_add);
                startActivityForResult(intent_add, RequestCode);
                break;
            //点击Item减号
            case R.id.shopcar_bt_listview_item_minus:
//                获取Adapter中设置的Tag
                if (tag != null && tag instanceof Integer) {
                    int position = (Integer) tag;
                    L.d("xiao", "position：" + position);
                    //更改数据源数据
                    L.d(L.TAG, "点击减号时数据源的大小：" + datas.size() + "");
                    int num = datas.get(position).getCount();
                    //获取商品的单价
                    String price = datas.get(position).getBean().getPrice();
                    if (num > 1) {
                        num--;
                        scanLists.get(position).remove(position);
                        datas.get(position).setCount(num);//修改集合中的商品数量
                        String scan = datas.get(position).getBean().getScan();//删除的商品的对应的二维码
                        new DBManger(this).deletesqlsql(scan);
                        adapter.notifyDataSetChanged();
                    } else if (num <= 1) {
                        showdialog(ShopCarActivity.this, position);
                    }
                }
                break;
            //清除购物车
            case R.id.shopcar_toolBar_tv_clean:
                datas.clear();
                new DBManger(this).deleteSQL();
                scanLists.clear();
                adapter.notifyDataSetChanged();
                break;
            //点击删除整类商品
            case R.id.shopcar_bt_listview_item_remove:
                if (tag != null && tag instanceof Integer) {
                    int position = (Integer) tag;
                    showdialog(ShopCarActivity.this, position);
                }
                break;
            //线上商城
            case R.id.shopcar_tv_mallCar:
                if (LoginActivity.isLogin) {
                    startActivity(new Intent(this, MallCarActivity.class));
                    finish();
                } else {
                    Intent intent1 = new Intent(this, LoginActivity.class);
                    intent1.putExtra("whereActivity", "WalletLogout");
                    startActivity(intent1);
                    finish();
                }
                break;
            case R.id.shopcar_tv_my:
                if (LoginActivity.isLogin) {
                    startActivity(new Intent(this, WalletActivity.class));
                    finish();
                } else {
                    startActivity(new Intent(this, WalletLogoutActivity.class));
                    finish();
                }
                break;
            case R.id.shopcar_tv_scan:
                mBoolean = true;
                Intent intent_merchant1 = new Intent(ShopCarActivity.this, CaptureActivity.class);
                Bundle bundle_merchant1 = new Bundle();
                bundle_merchant1.putString(Static.BundleKey, Static.BundleValue);
                intent_merchant1.putExtras(bundle_merchant1);
                startActivityForResult(intent_merchant1, RequestCode);
                break;
            case R.id.shopcar_tv_mall:
                if (LoginActivity.isLogin) {
                    startActivity(new Intent(this, MallActivity.class));
                    finish();
                } else {
                    Intent intent1 = new Intent(this, LoginActivity.class);
                    intent1.putExtra("whereActivity", "WalletLogout");
                    startActivity(intent1);
                    finish();
                }
                //智能酒柜
//            case R.id.shopcar_tv_gradevin:
//                if (LoginActivity.isLogin) {
//                    startActivity(new Intent(this, GradevinActivity.class));
//                    finish();
//                } else {
//                    Intent intent1 = new Intent(this, LoginActivity.class);
//                    intent1.putExtra("whereActivity", "WalletLogout");
//                    startActivity(intent1);
//                    finish();
//                }
//                break;
        }
    }

    private void showdialog(final ShopCarActivity shopCarActivity, final int position) {
        AlertDialog.Builder builder = new AlertDialog.Builder(shopCarActivity);
        View view = View.inflate(shopCarActivity, R.layout.confirmdialog_layout, null);
        builder.setView(view);
        TextView cancel = (TextView) view.findViewById(R.id.confirmDialog_cancel);
        TextView affirm = (TextView) view.findViewById(R.id.confirmDialog_affirm);
        final AlertDialog dialog = builder.create();
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        affirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String name = datas.get(position).getBean().getName();
                datas.remove(position);
                scanLists.remove(position);
                new DBManger(shopCarActivity).deleteOne(name);
                adapter.notifyDataSetChanged();
                dialog.dismiss();
            }
        });
        dialog.show();

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        adapter.unregisterDataSetObserver(sumObserver);
    }

    public void goLogin() {
        Intent intent = new Intent(ShopCarActivity.this, LoginActivity.class);
        intent.putExtra(Constant.formShopCar, Constant.formShopCar);
        startActivity(intent);
    }
}
